package com.why.server;

import com.why.enums.ErrorEnum;
import com.why.exception.RpcException;
import com.why.pool.ThreadPoolFactroy;
import com.why.pool.Worker;
import com.why.provider.ServiceRegistry;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;

/**
 * @program: why-rpc-framework
 * @description:
 * @author: @why
 * @create: 2021-03-15 16:00
 **/
@Slf4j
public class RpcServer {

    /**线程池**/
    private static ExecutorService poolService;
    private int port;
    private ServiceRegistry registry;

    public RpcServer(ServiceRegistry registry, int port) {
        this.registry = registry;
        this.port = port;
        poolService = ThreadPoolFactroy.getExecutorService();
    }

    public void start() {
        try {
            ServerSocket serverSocket;
            serverSocket = new ServerSocket(port);
            Socket accept;
            while (true) {
                /**此时服务端将会在这里阻塞,等待客户端连接**/
                accept = serverSocket.accept();
                if (accept != null) {
                    //将任务交其他线程去处理...
                    log.info("客户端:{}来了", accept.getLocalAddress() + ";" + accept.getPort());
                    log.info("服务端接收到请求信息,将任务交给线程池去处理");
                    poolService.execute(new Worker(accept,registry));
                }
            }


        } catch (IOException e) {
            log.error("在服务端这里发生了异常...");
            throw new RpcException(ErrorEnum.NOT_FOUND);
        }


    }


}